<script setup lang="ts">
import type { DemoTableApi } from '#/api/examples/table';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { addUserApi, updateUserApi } from '#/api';

const emit = defineEmits(['submit']);

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入用户名',
      },
      fieldName: 'username',
      label: '用户名',
      rules: 'required',
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: '请输入密码',
        autocomplete: true,
      },
      fieldName: 'password',
      label: '密码',
      rules: 'required',
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入真实姓名',
      },
      fieldName: 'realName',
      label: '真实姓名',
      rules: 'required',
    },
    {
      component: 'VbenSelect',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: 'super',
            value: 'super',
          },
          {
            label: 'admin',
            value: 'admin',
          },
          {
            label: 'user',
            value: 'user',
          },
        ],
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'roles',
      label: '角色',
      rules: 'required',
    },
  ],
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
    // modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values } = modalApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values, false);
      }
    }
  },
  title: '内嵌表单示例',
});

function onSubmit(values: Record<string, any>) {
  values.id
    ? updateUserApi(values as DemoTableApi.updateParams)
    : addUserApi(values as DemoTableApi.addParams);
  modalApi.close();
  emit('submit');
}
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>

<style scoped></style>
